package com.chuangshu.chuangshuteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chuangshu.chuangshuteam.config.BaseContext;
import com.chuangshu.chuangshuteam.dto.AssessmentQuestionsDTO;
import com.chuangshu.chuangshuteam.dto.FileMetadataDto;
import com.chuangshu.chuangshuteam.dto.Result;
import com.chuangshu.chuangshuteam.entity.AssessmentQuestions;
import com.chuangshu.chuangshuteam.entity.BusinessKey;
import com.chuangshu.chuangshuteam.entity.FileInfo;
import com.chuangshu.chuangshuteam.mapper.AssessmentQuestionsMapper;
import com.chuangshu.chuangshuteam.mapper.FileInfoMapper;
import com.chuangshu.chuangshuteam.service.AssessmentQuestionsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangshu.chuangshuteam.vo.AssessmentQuestionsVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author k
 * @since 2025-09-21
 */
@Service
public class AssessmentQuestionsServiceImpl extends ServiceImpl<AssessmentQuestionsMapper, AssessmentQuestions> implements AssessmentQuestionsService {
    @Autowired
     AssessmentQuestionsMapper assessmentQuestionsMapper;
    @Autowired
    FileInfoMapper fileInfoMapper;
    @Override
    @Transactional
    public void addQuestionsByRecruitmentCyclesId(AssessmentQuestionsVO assessmentQuestionsVO) {
        if (assessmentQuestionsVO.getFileMetadataDtos()== null|| assessmentQuestionsVO.getFileMetadataDtos().isEmpty()){
            addAssessmentQuestions(assessmentQuestionsVO);
        }else {
            AssessmentQuestions assessmentQuestions = addAssessmentQuestions(assessmentQuestionsVO);
            Long id = assessmentQuestions.getId();
            for (int i = 0; i < assessmentQuestionsVO.getFileMetadataDtos().size(); i++) {
                FileMetadataDto fileMetadataDTO = assessmentQuestionsVO.getFileMetadataDtos().get(i);
                FileInfo fileInfo = new FileInfo();
                BeanUtils.copyProperties(fileMetadataDTO,fileInfo);
                fileInfo.setBusinessId(id);
                fileInfo.setBusinessType(BusinessKey.ASSESSMENT_QUESTIONS_ID);
                fileInfoMapper.insert(fileInfo);
            }
        }
    }

    @Override
    public Result getByPage(Integer page, Integer pageSize) {
        Page<AssessmentQuestions> questionsPage = new Page<>(page, pageSize);

        QueryWrapper<AssessmentQuestions> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");
        Page<AssessmentQuestions> page1 = this.page(questionsPage, queryWrapper);

        Page<AssessmentQuestionsDTO> page2 = new Page<>(page, pageSize);
        page2.setTotal(page1.getTotal());
        page2.setPages(page1.getPages());

        List<AssessmentQuestionsDTO> DTOList = new ArrayList<>();
        for (AssessmentQuestions assessmentQuestions : page1.getRecords()) {
            AssessmentQuestionsDTO DTO = new AssessmentQuestionsDTO();
            BeanUtils.copyProperties(assessmentQuestions, DTO);
            DTOList.add(DTO);
        }
        page2.setRecords(DTOList);

        return Result.ok(page2);

    }   // 按创建时间降序排序

    @Override
    public List<AssessmentQuestionsDTO> getQuestionsByRecruitmentCyclesId(Long recruitmentCyclesId) {
        LambdaQueryWrapper<AssessmentQuestions> assessmentQuestionsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        assessmentQuestionsLambdaQueryWrapper.eq(AssessmentQuestions::getRecruitmentCycleId,recruitmentCyclesId);
        List<AssessmentQuestions> assessmentQuestions = assessmentQuestionsMapper.selectList(assessmentQuestionsLambdaQueryWrapper);
        List<AssessmentQuestionsDTO> DTOList = new ArrayList<>();
        for (AssessmentQuestions assessmentQuestions1 : assessmentQuestions) {
            AssessmentQuestionsDTO DTO = new AssessmentQuestionsDTO();
            BeanUtils.copyProperties(assessmentQuestions1, DTO);
            DTOList.add(DTO);
        }
        return DTOList;
    }

    @Override
    public AssessmentQuestionsDTO queryById(Long id) {
        return assessmentQuestionsMapper.queryById(id, BusinessKey.ASSESSMENT_QUESTIONS_ID);
    }


    private AssessmentQuestions addAssessmentQuestions(AssessmentQuestionsVO assessmentQuestionsVO){
        AssessmentQuestions assessmentQuestions = new AssessmentQuestions();
        assessmentQuestionsVO.setCreatedBy(BaseContext.getCurrentId());
        BeanUtils.copyProperties(assessmentQuestionsVO,assessmentQuestions);
        assessmentQuestionsMapper.insert(assessmentQuestions);
        return assessmentQuestions;
    }

    @Override
public Result updateQuestions(AssessmentQuestionsVO assessmentQuestionsVO) {
    // 检查必要字段
    if (assessmentQuestionsVO.getId() == null || assessmentQuestionsVO.getId() <= 0) {
        return Result.fail("请提供有效的面试题ID");
    }
    if (assessmentQuestionsVO.getTitle() == null || assessmentQuestionsVO.getTitle().isEmpty()) {
        return Result.fail("请填写标题");
    }
    if (assessmentQuestionsVO.getDescription() == null || assessmentQuestionsVO.getDescription().isEmpty()) {
        return Result.fail("请填写内容");
    }
    if (assessmentQuestionsVO.getRoundNumber() == null || assessmentQuestionsVO.getRoundNumber() <= 0) {
        return Result.fail("请填写正确的面试轮数");
    }
    if (assessmentQuestionsVO.getRecruitmentCycleId() == null || assessmentQuestionsVO.getRecruitmentCycleId() <= 0) {
        return Result.fail("请填写正确的招聘周期ID");
    }

    // 检查题目是否存在
    AssessmentQuestions existingQuestion = this.getById(assessmentQuestionsVO.getId());
    if (existingQuestion == null) {
        return Result.fail("面试题不存在");
    }

    // 更新题目信息
    BeanUtils.copyProperties(assessmentQuestionsVO, existingQuestion);
    existingQuestion.setCreatedBy(BaseContext.getCurrentId()); // 设置更新人，实际项目中应从上下文中获取当前用户ID
    this.updateById(existingQuestion);

    return Result.ok("更新成功");
}


@Transactional
@Override
public Result deleteQuestionsById(Long id) {
    // 检查参数
    if (id == null || id <= 0) {
        return Result.fail("请提供有效的面试题ID");
    }

    // 检查题目是否存在
    AssessmentQuestions existingQuestion = this.getById(id);
    if (existingQuestion == null) {
        return Result.fail("面试题不存在");
    }

    // 删除关联的文件
    QueryWrapper<FileInfo> fileQueryWrapper = new QueryWrapper<>();
    fileQueryWrapper.eq("business_id", id);
    fileQueryWrapper.eq("business_type", BusinessKey.ASSESSMENT_QUESTIONS_ID);
    fileInfoMapper.delete(fileQueryWrapper);

    // 删除面试题
    this.removeById(id);

    return Result.ok("删除成功");
}


}
